import cv2
import numpy as np

def apply_sobel(img):
    blurred = cv2.GaussianBlur(img, (3, 3), 0)
    sobelx = cv2.Sobel(blurred, cv2.CV_64F, 1, 0, ksize=3)
    sobely = cv2.Sobel(blurred, cv2.CV_64F, 0, 1, ksize=3)
    sobel_mag = np.sqrt(sobelx**2 + sobely**2)
    sobel_mag = cv2.normalize(sobel_mag, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)
    return sobel_mag


def apply_morphology(img):
    kernel = np.ones((1, 1), np.uint8) 
    opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)  # 开运算去除小噪点
    edges = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel) # 闭运算填充小孔
    return edges

img1 = cv2.imread('image1.jpg', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('image3.jpg', cv2.IMREAD_GRAYSCALE)

sobel_img1 = apply_sobel(img1)
sobel_img2 = apply_sobel(img2)

sobel_img1 = apply_morphology(sobel_img1)
sobel_img2 = apply_morphology(sobel_img2)

_, sobel_img1_bin = cv2.threshold(sobel_img1, 30, 255, cv2.THRESH_BINARY)
_, sobel_img2_bin = cv2.threshold(sobel_img2, 30, 255, cv2.THRESH_BINARY)

combined_img = cv2.cvtColor(img1, cv2.COLOR_GRAY2BGR)

combined_img[np.where((sobel_img2_bin == 255))] = [0, 0, 255]  # 红色表示第二幅图像的边缘
combined_img[np.where((sobel_img1_bin == 255))] = [0, 255, 0]  # 绿色表示第一幅图像的边缘

# cv2.imshow('Image 1', img1)
# cv2.imshow('Image 2', img2)
# cv2.imshow('Combined Edges', combined_img)
cv2.imwrite("sobel_output_3.jpg",combined_img)

# cv2.waitKey(0)
# cv2.destroyAllWindows()